import useSWR, { mutate, ConfigInterface } from 'swr'
import { cloud, showLoading, showToast, hideLoading } from 'remax/wechat'

interface CloudResponse {
  result: any
  requestID: string
}

export default (
  name: string | null,
  data?: object,
  config?: ConfigInterface<any>
) => {
  const key: string | null = name ? JSON.stringify({ name, data }) : null
  const fetcher = (key: string): Promise<any> => {
    showLoading({ title: '载入中', mask: true })
    return cloud
      .callFunction(JSON.parse(key))
      .then((response: CloudResponse) => {
        hideLoading()
        return response.result
      })
      .catch((e: any) => {
        hideLoading()
        showToast({ title: '网络错误', icon: 'none' })
        throw e
      })
  }

  return useSWR(key, fetcher, { dedupingInterval: 30000, ...config })
}

export const mutateCloud = (name: string, data?: object, ...rest: any[]) => {
  const key = JSON.stringify({ name, data })
  return mutate(key, ...rest)
}

export const requestCloud = (name: string, data?: object): Promise<any> => {
  showLoading({ title: '载入中', mask: true })
  return cloud
    .callFunction({ name, data })
    .then((response: CloudResponse) => {
      hideLoading()
      return response.result
    })
    .catch((e: any) => {
      hideLoading()
      throw e
    })
}
